#include <arpa/inet.h>
#include <cstdint>
#include <cstring>
#include<iostream>
#include <memory>
#include <netinet/in.h>
#include <string>
#include <strings.h>
#include <sys/socket.h>
#include"ThreadPool/Thread.hpp"

uint16_t serverport=0;
std::string serverip;

static void* udpSend(void* args)
{
    int sock=*(int*)((ThreadData*)args)->_args;
    std::string name=((ThreadData*)args)->_name;
    std::string buffer;
    struct sockaddr_in server;
    socklen_t len=sizeof(server);
    bzero(&server,sizeof(server));
    server.sin_family=AF_INET;
    server.sin_port=htons(serverport);
    server.sin_addr.s_addr=inet_addr(serverip.c_str());
    while(true)
    {
        std::cerr<<"请输入您的信息"<<std::endl;
        std::getline(std::cin,buffer);
        sendto(sock, (struct sockaddr*)&server, sizeof(server), 
        0, (struct sockaddr*)&server, len);
    }
}
static void* udpRecv(void* args)
{
    int sock=*(int*)((ThreadData*)args)->_args;
    std::string name=((ThreadData*)args)->_name;
    char buffer[1024];
    while(true)
    {
        memset(buffer, 0, sizeof(buffer));
        struct sockaddr_in temp;
        socklen_t len=sizeof(temp);
        ssize_t s=recvfrom(sock, buffer, sizeof(buffer), 0, 
        (struct sockaddr*)&temp, &len);
        if(s > 0)
        {
            buffer[s]=0;
            std::cout<<buffer<<std::endl;
        }
    }
}

int main(int argc,const char* argv[])
{
    if(argc!=3){
        exit(2);
    }
    int sock=socket(AF_INET, SOCK_DGRAM, 0);
    //从主线程这里接受到的就是字符串
    serverip=argv[1];
    serverport=atoi(argv[2]);
    std::unique_ptr<Thread> sender(new Thread(1,udpSend,(void*)&sock));
    std::unique_ptr<Thread> recver(new Thread(1,udpSend,(void*)&sock));
    sender->start();
    recver->join();
    sender->start();
    recver->join();
    return 0;
}